package bid.test;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import java.io.*;
import java.net.*;
import java.net.http.*;

/**
 * @author oldliu
 * @since 1.0
 */
public class HttpClientExample {
    public static void main(String[] args) {

        String str = testa("合肥工业大学屯溪路校区");
        if (str == null) {
            return;
        }
        JSONObject jsonObject = JSON.parseObject(str);

        Integer status = jsonObject.getInteger("status");
        if (status != 0) {
            System.out.println("没找到地址");
            return;
        }
        String jingdu = jsonObject.getJSONObject("result").getJSONObject("location").getString("lng");
        String weidu = jsonObject.getJSONObject("result").getJSONObject("location").getString("lat");

        System.out.printf("这个地址：纬度是" + weidu + ",经度是 " + jingdu);

    }

    public static String testa(String addr) {

        try {
            // 创建URL对象
            URL url = new URL("http://api.map.baidu.com/geocoder/v2/?address=" + addr + "&output=json&ak" +
                    "=B4bd9e22c0a580cd04b0e84b17bf9eb6");

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("GET");

            // 设置请求头
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");

            connection.connect();
            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("响应码： " + responseCode);

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }

            // 关闭连接和输入流
            in.close();
            connection.disconnect();

            // 输出响应内容
            System.out.println("响应内容： " + content.toString());
            return content.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void aaa(String[] args) throws Exception {
        // 创建HttpClient对象
        HttpClient client = HttpClient.newHttpClient();

        // 创建HttpRequest对象，并设置请求类型为GET
        HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI("http://api.map.baidu.com/geocoder/v2/?address=阜阳师范大学&output=json&ak" +
                        "=B4bd9e22c0a580cd04b0e84b17bf9eb6")) // 替换成你要请求的URL
                .build();

        // 使用HttpClient发送HttpRequest，并获取HttpResponse
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // 输出响应的状态码和响应体
        System.out.println("Response Code: " + response.statusCode());
        System.out.println("Response Body: " + response.body());
    }
}
